package com.sharemarking.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.system.dto.Page;
import com.sharemarking.system.dto.orgManagement.OrgVerifyInfoDto;
import com.sharemarking.system.dto.orgVerify.OrgVerifyListDto;
import com.sharemarking.system.mapper.OrgMapper;
import com.sharemarking.system.mapper.OrgVerifyMapper;
import com.sharemarking.system.mapper.OrgWasteTypeMapper;
import com.sharemarking.system.mapper.WasteTypeMapper;
import com.sharemarking.wa.common.entity.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author dxy
 */
@Controller
@RequestMapping("system/manageManagement")
public class ManageManagementController {
    @Autowired
    private OrgVerifyMapper om;
    @Autowired
    private HttpSession session;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private OrgWasteTypeMapper orgWasteTypeMapper;
    @Autowired
    private WasteTypeMapper wasteTypeMapper;


    /**
     * 列表页面
     * @param
     * @param model
     */
    @GetMapping("index")
    @PreAuthorize("hasPermission('base','all')")
    public String index(OrgVerifyListDto obj, Integer page, Model model, Integer isSession){
        int size=10;
        if(page==null) {
            page=0;
        }
        // session 参数回显
        if (isSession != null) {
            // 如果isSession为1，代表要从session取条件参数，一般应用在某操作之后要保存查询参数
            obj = session.getAttribute("query") == null ? obj : (OrgVerifyListDto) session.getAttribute("query");
            size = session.getAttribute("size") == null ? size : (int) session.getAttribute("size");
            page = session.getAttribute("page") == null ? page : (int) session.getAttribute("page");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("pageIndex",page*size);
        map.put("pageSize",size);
        map.put("verify",1);
        if(!StringUtils.isEmpty(obj.getMobile())) {
            map.put("mobile",obj.getMobile());
        }
        if(!StringUtils.isEmpty(obj.getOrgName())) {
            map.put("orgName",obj.getOrgName());
        }
        if(!StringUtils.isEmpty(obj.getIsMonthlyPay())) {
            map.put("isMonthlyPay",obj.getIsMonthlyPay());
        }
        List<OrgVerifyListDto> list=om.getManagementOrgList(map);
        int total = om.getManagementOrgListTotal(map);
        model.addAttribute("page", new Page<>(page, size, total, list));
        model.addAttribute("query",obj);
        // session 参数保存
        session.setAttribute("query",obj);
        session.setAttribute("size", size);
        session.setAttribute("page", page);
        return "orgManagement/managementIndex";
    }


    /**
     * 新增、编辑页面
     * @param obj
     * @param model
     * @return
     */
    @GetMapping("{id}")
    @PreAuthorize("hasPermission('base','all')")
    public String get(@PathVariable("id")int id, Model model){
        OrgVerifyInfoDto obj = new OrgVerifyInfoDto();
        if (id > 0) {
            obj = om.getInfo(id);
        }else {
            model.addAttribute("obj",obj);
            return "orgManagement/managementFormInsert";
        }
        List<String> wasteTypeLis = om.getOrgWasteTypeList(id);

        model.addAttribute("obj",obj);
        model.addAttribute("wasteTypeListStr",String.join(",",wasteTypeLis));
        return "orgManagement/managementForm";
    }

    /**
     * 新增、编辑
     * @param obj
     * @param model
     * @return
     */
    @PostMapping("{id}")
    @PreAuthorize("hasPermission('base','all')")
    @Transactional
    public String post(OrgVerifyInfoDto obj, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) throws Exception{

        //企业认证转换
        OrgVerify orgVerify = new OrgVerify();
        BeanUtils.copyProperties(obj,orgVerify);

        //更新用户表
        Member member = new Member();
        member.setMobile(obj.getMobile());
        member.setRealName(obj.getMemberName());
        member.setNickName("手机尾号" + member.getMobile().substring(member.getMobile().length() - 4));
        member.setHeadImg("headImg/memberBigHead.png");
        //更新企业表
        Org org = new Org();
        org.setName(obj.getName());
        org.setRealName(obj.getName());
        org.setIsMonthlyPay(obj.getIsMonthlyPay());

        if (obj.getId() == 0) {
            if (om.isBindMobile(obj.getMobile())!=0){
                redirectAttributes.addFlashAttribute("msg","该手机号已经绑定其它单位！");
                return "redirect:"+obj.getId();
            }


            //插入用户
            member.setRole(1);//经营端
            member.setCreateDate(new Date());
            member.setPassword("96e79218965eb72c92a549dd5a330112");//默认密码111111
            member.setAlias(UUID.randomUUID().toString().replaceAll("-", ""));
            om.insertMember(member);

            //新插入企业
            org.setCreateDate(new Date());
            org.setMemberId(member.getId());
            om.insertOrg(org);

            //插入认证企业
            orgVerify.setOrgId(org.getId());
            orgVerify.setMemberId(member.getId());
            orgVerify.setExamState(1);//已通过
            orgVerify.setCreateDate(new Date());
            om.insert(orgVerify);

            //插入企业用户表
            om.insertOrgMember(org.getId(),member.getId());
        }else {
            Integer memberId = om.getMemberId(obj.getId());
            if (om.isBindMobileByMemberId(obj.getMobile(),memberId)!=1){
                if (om.isBindMobile(obj.getMobile())!=0){
                    redirectAttributes.addFlashAttribute("msg","该手机号已经绑定其它单位！");
                    return "redirect:"+obj.getId();
                }
            }

            //更新企业认证表
            orgVerify.setUpdateDate(new Date());
            om.updateById(orgVerify);

            //更新企业表
            org.setId(obj.getOrgId());
            orgMapper.updateById(org);

            //更新用户表
            member.setId(memberId);
            member.setUpdateDate(new Date());
            om.updateMember(member);
        }

        String wasteTypeListStr = request.getParameter("wasteTypeListStr");
        if (!StringUtils.isEmpty(wasteTypeListStr)) {
            orgWasteTypeMapper.delete(new QueryWrapper<OrgWasteType>().eq("org_verify_id", orgVerify.getId()).eq("org_id", org.getId()));
            String[] wasteTypeList = wasteTypeListStr.split(",");
            for (String s : wasteTypeList) {
                OrgWasteType orgWasteType = new OrgWasteType();
                orgWasteType.setOrgId(org.getId());
                orgWasteType.setOrgVerifyId(orgVerify.getId());
                orgWasteType.setWasteTypeName(s);
                orgWasteType.setWasteTypeId(wasteTypeMapper.selectOne(new QueryWrapper<WasteType>().eq("name", s)).getId());
                orgWasteType.setCreateDate(new Date());
                orgWasteTypeMapper.insert(orgWasteType);
            }
        }

        model.addAttribute("obj",obj);
        redirectAttributes.addFlashAttribute("msg","操作成功!");
        return "redirect:index?isSession=1";
    }


    /**
     * 详情页面
     * @param obj
     * @param model
     * @return
     */
    @GetMapping("info/{id}")
    @PreAuthorize("hasPermission('base','all')")
    public String getInfo(@PathVariable("id")int id, Model model){
        OrgVerify obj = new OrgVerify();
        if (id > 0) {
            obj = om.selectById(id);
        }else {
            model.addAttribute("obj",obj);
        }
        List<String> attach = om.getAttachList(id);
        model.addAttribute("attach",attach);
        model.addAttribute("obj",obj);
        return "orgVerify/info";
    }

    /**
     * 审核
     * @param obj
     * @param model
     * @return
     */
    @GetMapping("exam")
    @PreAuthorize("hasPermission('base','all')")
    @Transactional
    public String exam(int id, int type, String rejectReason, Model model, RedirectAttributes redirectAttributes){
        OrgVerify orgVerify = new OrgVerify();
        orgVerify.setExamState(type);
        if(type == 2) {
            if(StringUtils.isEmpty(rejectReason)) {
                redirectAttributes.addFlashAttribute("msg","驳回理由不可为空！");
                return "redirect:index?isSession=1";
            }
            orgVerify.setRejectReason(rejectReason);
        }else {
            orgVerify.setRejectReason(null);
        }
        orgVerify.setId(id);
        orgVerify.setUpdateDate(new Date());
        om.updateById(orgVerify);
        redirectAttributes.addFlashAttribute("msg","操作成功！");
        return "redirect:index?isSession=1";
    }
}
